package com.a4studio.android.newsreader;

import java.util.List;

import com.a4studio.android.util.ContentReader;
import com.a4studio.android.util.NewsItem;
import com.a4studio.android.util.NewsPersistence;
import com.a4studio.android.util.YahooNewsCrawler;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class NewsFetchService extends Service {
	
	private final static String TAG = NewsFetchService.class.getSimpleName();

	private YahooNewsCrawler crawler;
	private ContentReader reader;
	private NewsPersistence store;
	
	private Runnable task;
	private Preferences prefs;
	
	/* (non-Javadoc)
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		//TODO: add the keyword retrieval from preference
		Log.d(TAG, "onCreate");
		prefs = new Preferences(this);
		crawler = new YahooNewsCrawler(prefs.getKeywordSetting(),prefs.getResultNumSetting()+1);
		reader = new ContentReader();
		try {
			store = new NewsPersistence();
		} catch (Exception e) {
			Log.e(TAG, "store initialization fail", e);
		}
		
		
		
	}

	/* (non-Javadoc)
	 * @see android.app.Service#onStart(android.content.Intent, int)
	 */
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Log.d(TAG, "onStart");
		task = new Runnable()
		{

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Log.d(TAG, "crawler.search() start");
				crawler.search();
				List<NewsItem> items = crawler.getNewsResults();
				for(NewsItem item : items)
				{
					String url = item.getUrl();
					reader.setUrl(url);
					try {						
						item.setContent(reader.getResult());
						Log.d(TAG, "reader.getResult() done");
						store.storeNewsItem(item);
						Thread.sleep(15*1000);
						Log.d(TAG, "store.storeNewsItem done");
					} catch (Exception e) {
						Log.e(TAG, "store NewsItem fail", e);
					}

				}
			}
			
		};
		
		new Thread(task).run();
		
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/* (non-Javadoc)
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}



}
